import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Ref } from 'vue'
import axios from 'axios'

export interface Message {
  role: 'user' | 'assistant' | 'system'
  content: string
  timestamp?: number
  tokens?: number
  promptTokens?: number
  completionTokens?: number
  responseTime?: number
}

export interface ChatSession {
  id: string
  title: string
  model: string
  messages: Message[]
  createdAt: number
  updatedAt: number
}

export interface AIModel {
  id: string
  name: string
  hasDeepThinking: boolean
}

// 默认模型ID
const DEFAULT_MODEL_ID = 'deepseek-v3'

export const useChatStore = defineStore('chat', () => {
  // 状态
  const currentSession: Ref<ChatSession | null> = ref(null)
  const chatHistory: Ref<ChatSession[]> = ref([])
  const availableModels: Ref<AIModel[]> = ref([])
  const enabledModelIds: Ref<string[]> = ref([])
  const isLoading = ref(false)
  const deepThinkingEnabled = ref(false)
  const elderlyModeEnabled = ref(false) // 适老化模式状态

  // 计算属性
  const currentMessages = computed(() => currentSession.value?.messages || [])
  const enabledModels = computed(() => {
    if (enabledModelIds.value.length === 0) {
      return availableModels.value
    }
    return availableModels.value.filter(model => enabledModelIds.value.includes(model.id))
  })
  
  // 获取可用的AI模型
  async function fetchModels() {
    try {
      const response = await axios.get('/api/models')
      if (response.data.success) {
        availableModels.value = response.data.data
      } else {
        // 如果API请求失败，使用默认模型列表
        availableModels.value = [
          { id: 'gpt-3.5-turbo', name: 'GPT-3.5', hasDeepThinking: false },
          { id: 'gpt-4', name: 'GPT-4', hasDeepThinking: false },
          { id: 'deepseek-v3', name: 'DeepSeek V3', hasDeepThinking: true },
          { id: 'deepseek-r1', name: 'DeepSeek R1', hasDeepThinking: true },
          { id: DEFAULT_MODEL_ID, name: 'DeepSeek', hasDeepThinking: true }
        ]
      }
      
      // 如果没有已启用的模型，默认只启用deepseek-v3和deepseek-r1
      if (enabledModelIds.value.length === 0) {
        enabledModelIds.value = availableModels.value
          .filter(model => model.id === 'deepseek-v3' || model.id === 'deepseek-r1')
          .map(model => model.id)
        
        // 如果没有找到这两个模型，则默认启用第一个模型
        if (enabledModelIds.value.length === 0 && availableModels.value.length > 0) {
          enabledModelIds.value = [availableModels.value[0].id]
        }
        
        saveModelSettings()
      }
    } catch (error) {
      console.error('获取模型列表失败:', error)
      // 出错时使用默认模型列表
      availableModels.value = [
        { id: 'gpt-3.5-turbo', name: 'GPT-3.5', hasDeepThinking: false },
        { id: 'gpt-4', name: 'GPT-4', hasDeepThinking: false },
        { id: 'deepseek-v3', name: 'DeepSeek V3', hasDeepThinking: true },
        { id: 'deepseek-r1', name: 'DeepSeek R1', hasDeepThinking: true },
        { id: DEFAULT_MODEL_ID, name: 'DeepSeek', hasDeepThinking: true }
      ]
      
      // 如果没有已启用的模型，默认只启用deepseek-v3和deepseek-r1
      if (enabledModelIds.value.length === 0) {
        enabledModelIds.value = availableModels.value
          .filter(model => model.id === 'deepseek-v3' || model.id === 'deepseek-r1')
          .map(model => model.id)
        
        // 如果没有找到这两个模型，则默认启用第一个模型
        if (enabledModelIds.value.length === 0 && availableModels.value.length > 0) {
          enabledModelIds.value = [availableModels.value[0].id]
        }
        
        saveModelSettings()
      }
    }
  }

  // 更新已启用的模型
  function updateEnabledModels(modelIds: string[]) {
    enabledModelIds.value = modelIds
    saveModelSettings()
    
    // 如果当前模型不在启用列表中，切换到第一个启用的模型
    if (currentSession.value && !modelIds.includes(currentSession.value.model)) {
      if (modelIds.length > 0) {
        currentSession.value.model = modelIds[0]
        saveToLocalStorage()
      }
    }
  }
  
  // 保存模型设置
  function saveModelSettings() {
    localStorage.setItem('enabledModelIds', JSON.stringify(enabledModelIds.value))
  }
  
  // 加载模型设置
  function loadModelSettings() {
    const savedModelIds = localStorage.getItem('enabledModelIds')
    if (savedModelIds) {
      try {
        enabledModelIds.value = JSON.parse(savedModelIds)
      } catch (e) {
        console.error('解析模型设置失败:', e)
        enabledModelIds.value = []
      }
    }
  }

  // 切换适老化模式
  function toggleElderlyMode() {
    // 直接设置新值而不是取反，避免可能的引用问题
    const newValue = !elderlyModeEnabled.value
    elderlyModeEnabled.value = newValue
    
    // 先保存到本地存储
    localStorage.setItem('elderlyModeEnabled', newValue.toString())
    
    // 强制更新DOM和重新渲染
    document.body.classList.toggle('elderly-mode', newValue)
    document.body.classList.add('elderly-mode-force-update')
    
    // 强制刷新应用状态 - 使用时间戳确保每次值都不同
    localStorage.setItem('app_last_update', Date.now().toString())
    
    // 手动触发事件，确保其他组件能够监听到变化
    window.dispatchEvent(new StorageEvent('storage', {
      key: 'elderlyModeEnabled',
      newValue: newValue.toString(),
      storageArea: localStorage
    }))
    
    console.log('适老化模式已切换:', newValue)
    
    // 触发重新渲染
    setTimeout(() => {
      window.dispatchEvent(new Event('resize'))
      document.body.classList.remove('elderly-mode-force-update')
    }, 50)
  }

  // 保存适老化模式设置
  function saveElderlyModeSetting() {
    localStorage.setItem('elderlyModeEnabled', elderlyModeEnabled.value.toString())
    console.log('保存适老化模式设置:', elderlyModeEnabled.value)
  }

  // 加载适老化模式设置
  function loadElderlyModeSetting() {
    const savedMode = localStorage.getItem('elderlyModeEnabled')
    if (savedMode !== null) {
      elderlyModeEnabled.value = savedMode === 'true'
    }
  }

  // 创建新的聊天会话
  function createNewSession(modelId: string = DEFAULT_MODEL_ID) {
    const newSession: ChatSession = {
      id: Date.now().toString(),
      title: '新对话',
      model: modelId,
      messages: [],
      createdAt: Date.now(),
      updatedAt: Date.now()
    }
    currentSession.value = newSession
    chatHistory.value.unshift(newSession)
    
    // 只保留最近10天的历史记录
    const tenDaysAgo = Date.now() - 10 * 24 * 60 * 60 * 1000
    chatHistory.value = chatHistory.value.filter(session => session.createdAt >= tenDaysAgo)
    
    // 保存到本地存储
    saveToLocalStorage()
    
    return newSession
  }

  // 发送消息
  async function sendMessage(content: string) {
    if (!currentSession.value || !content.trim()) return
    
    // 添加用户消息
    const userMessage: Message = {
      role: 'user',
      content,
      timestamp: Date.now()
    }
    currentSession.value.messages.push(userMessage)
    currentSession.value.updatedAt = Date.now()
    
    // 更新本地存储
    saveToLocalStorage()
    
    // 发送到API
    isLoading.value = true
    const startTime = Date.now()
    try {
      const options = currentSession.value.model.includes('deepseek') && deepThinkingEnabled.value
        ? { deep_thinking: true }
        : {}
      
      const response = await axios.post('/api/chat', {
        model: currentSession.value.model,
        messages: currentSession.value.messages,
        options,
        userId: 'anonymous' // 可以替换为实际用户ID
      })
      
      if (response.data.success) {
        const responseTime = Date.now() - startTime
        console.log('API响应:', response.data)
        
        // 添加AI回复
        const aiMessage: Message = {
          role: 'assistant',
          content: response.data.data.content,
          timestamp: Date.now(),
          tokens: response.data.data.tokens || 0,
          promptTokens: response.data.data.promptTokens || 0,
          completionTokens: response.data.data.completionTokens || 0,
          responseTime: responseTime
        }
        currentSession.value.messages.push(aiMessage)
        currentSession.value.updatedAt = Date.now()
        
        // 如果是第一条消息，更新会话标题
        if (currentSession.value.messages.length === 2) {
          // 提取第一条用户消息作为标题，并进行智能精简
          const userFirstMessage = content.trim();
          let title = '';
          
          // 如果消息很短，直接使用
          if (userFirstMessage.length <= 20) {
            title = userFirstMessage;
          } else {
            // 尝试提取前两个句子或短语
            const sentences = userFirstMessage.split(/[.!?。！？]/);
            if (sentences[0].length <= 25) {
              title = sentences[0];
            } else {
              // 如果第一句话太长，截取前20个字符
              title = userFirstMessage.slice(0, 20) + '...';
            }
          }
          
          currentSession.value.title = title;
        }
        
        // 更新本地存储
        saveToLocalStorage()
      }
    } catch (error) {
      console.error('发送消息失败:', error)
      // 添加错误消息
      const errorMessage: Message = {
        role: 'assistant',
        content: '抱歉，发送消息失败，请稍后重试。',
        timestamp: Date.now()
      }
      currentSession.value.messages.push(errorMessage)
      saveToLocalStorage()
    } finally {
      isLoading.value = false
    }
  }

  // 切换会话
  function switchSession(sessionId: string) {
    const session = chatHistory.value.find(s => s.id === sessionId)
    if (session) {
      currentSession.value = session
    }
  }

  // 删除会话
  function deleteSession(sessionId: string) {
    chatHistory.value = chatHistory.value.filter(s => s.id !== sessionId)
    if (currentSession.value?.id === sessionId) {
      currentSession.value = chatHistory.value[0] || null
    }
    saveToLocalStorage()
  }

  // 清除所有历史记录
  function clearAllHistory() {
    chatHistory.value = []
    currentSession.value = null
    saveToLocalStorage()
    // 创建一个新会话
    createNewSession(DEFAULT_MODEL_ID)
  }

  // 保存到本地存储
  function saveToLocalStorage() {
    localStorage.setItem('chatHistory', JSON.stringify(chatHistory.value))
    localStorage.setItem('currentSessionId', currentSession.value?.id || '')
  }

  // 从本地存储加载
  function loadFromLocalStorage() {
    const savedHistory = localStorage.getItem('chatHistory')
    const currentSessionId = localStorage.getItem('currentSessionId')
    
    if (savedHistory) {
      try {
        chatHistory.value = JSON.parse(savedHistory)
        
        // 只保留最近10天的历史记录
        const tenDaysAgo = Date.now() - 10 * 24 * 60 * 60 * 1000
        chatHistory.value = chatHistory.value.filter(session => session.createdAt >= tenDaysAgo)
        
        if (currentSessionId) {
          currentSession.value = chatHistory.value.find(s => s.id === currentSessionId) || chatHistory.value[0] || null
        } else {
          currentSession.value = chatHistory.value[0] || null
        }
      } catch (e) {
        console.error('解析本地存储数据失败:', e)
        chatHistory.value = []
        currentSession.value = null
      }
    }
  }

  // 初始化
  function init() {
    loadFromLocalStorage()
    loadModelSettings()
    loadElderlyModeSetting() // 加载适老化模式设置
    fetchModels()
    
    // 如果没有当前会话，创建一个新会话使用默认模型
    if (!currentSession.value) {
      createNewSession(DEFAULT_MODEL_ID)
    }
  }

  return {
    currentSession,
    chatHistory,
    availableModels,
    enabledModels,
    enabledModelIds,
    isLoading,
    deepThinkingEnabled,
    elderlyModeEnabled, // 导出适老化模式状态
    currentMessages,
    fetchModels,
    updateEnabledModels,
    createNewSession,
    sendMessage,
    switchSession,
    deleteSession,
    clearAllHistory,
    saveToLocalStorage,
    toggleElderlyMode, // 导出切换适老化模式的方法
    init
  }
}) 